﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class ConnectObj : MonoBehaviour
{
    public RectTransform RectObj;
    public Text Name;

    private void Awake()
    {
        RectObj = transform.GetComponent<RectTransform>();
        Name = transform.Find("Name").GetComponent<Text>();
    }

}

public class GameConnectPanel : MonoBehaviour
{
    private bool run;
    IDictionary<int, ConnectObj> nameID2HeadsLst = new Dictionary<int, ConnectObj>();
    IDictionary<int, bool> curID2Active = new Dictionary<int, bool>();

    private IDictionary<int, StartPre> nameID2StarPre = new Dictionary<int, StartPre>(); 
    void Awake()
    {
        Transform layout = transform.Find("Layout");

        int childCount = layout.childCount;

        
        for (int i = 0; i < childCount; i++)
        {
            Transform child = layout.GetChild(i);

            string childName = child.name.Split('-')[1];
            
            if(string.IsNullOrEmpty(childName))
                continue;

            int index = TryGetInt(childName);

            if(index<= -1)
                continue;

            nameID2HeadsLst[index] = child.gameObject.AddComponent<ConnectObj>();

            curID2Active[index] = false;
            child.gameObject.SetActive(false);
        }


        Transform layout2 = transform.parent.transform.Find("PlayerConnect").Find("Layout");
        childCount = layout2.childCount;

        for (int i = 0; i < childCount; i++)
        {
            Transform child = layout2.GetChild(i);
            string childName = child.name.Split('-')[1];

            if (string.IsNullOrEmpty(childName))
                continue;

            int index = TryGetInt(childName);

            if (index <= -1)
                continue;

            nameID2StarPre[index] = child.GetComponent<StartPre>();
        }

        run = true;
    }

    int TryGetInt(string str)
    {
        int result = -1;
        int.TryParse(str, out result);

        return result;
    }

    void Start () {
		
	}

  
    void Update ()
    {
        if (!run)
            return;

        if(!transform.gameObject.activeInHierarchy)
            return;

        foreach (var kv in nameID2StarPre)
        {
            if (kv.Value.bConnected)
            {
                nameID2HeadsLst[kv.Key].gameObject.SetActive(true);
                nameID2HeadsLst[kv.Key].Name.text = kv.Value.transform.Find("Text").GetComponent<Text>().text;
            }
            else
            {
                nameID2HeadsLst[kv.Key].gameObject.SetActive(false);
            }
        }
    }
}
